#include <iostream>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/base/CountDownLatch.h>
#include <unordered_map>

class Client
{
public:
    Client(int port) : _loop(_loopThread.startLoop()),
                       _client(_loop, muduo::net::InetAddress("127.0.0.1", port), "Client"),
                       _latch(1)
    {
        _client.setConnectionCallback(std::bind(&Client::OnConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&Client::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.connect();
        _latch.wait();
    }

    void send(const std::string &msg)
    {
        if (_conn->connected())
            _conn->send(msg);
        else
        {
            std::cout << "连接有错误" << std::endl;
        }
    }

    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected()==true)
        {
            std::cout << "Connected" << std::endl;
            _conn = conn;
            _latch.countDown(); // 计数--，为
        }
        else
        {
            _conn.reset();
            std::cout << "Disconnected" << std::endl;
        }
    }
    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp time)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << "Received :" << msg << std::endl;
    }

private:
    muduo::net::EventLoopThread _loopThread;
    muduo::net::EventLoop *_loop;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _latch;
    muduo::net::TcpClient _client;
};

int main()
{
    Client client(8888);
    while (1)
    {
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }

    return 0;
}